import React, { PureComponent } from 'react';
import { connect } from 'react-redux'
import Topic from './components/Topic';
import List from './components/List';
import Recommend from './components/Recommend';
import Writer from './components/Writer';
import { actionCreators } from './store'
import {
    HomeWrapper,
    HomeLeft,
    HomeRight,
    BackTop
} from './style';
class Home extends PureComponent {
    handleScrollTop() {
        window.scrollTo(0, 0)
    }
    render() {
        return (
            <HomeWrapper>
                <HomeLeft>
                    <img className='banner-img' alt='' src="//upload.jianshu.io/admin_banners/web_images/4318/60781ff21df1d1b03f5f8459e4a1983c009175a5.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540" />
                    <Topic />
                    <List />
                </HomeLeft>
                <HomeRight>
                    <Recommend />
                    <Writer />
                </HomeRight>
                {this.props.showTop ? <BackTop onClick={this.handleScrollTop}>顶部</BackTop> : null}
            </HomeWrapper>
        )
    }
    componentDidMount() {
        this.props.getHomeData()
        this.bindEvents()
    }
    componentWillUnmount() {
        window.removeEventListener('scroll', this.props.changeShowScrollTop)
    }
    bindEvents() {
        window.addEventListener('scroll', this.props.changeShowScrollTop)
    }
}

const mapState = (state) => ({
    showTop: state.get('home').get('showTop')
})

const mapDispatch = (dispatch) => ({
    getHomeData() {
        dispatch(actionCreators.getHomeData())
    },
    // 控制返回顶部按钮是否显示
    changeShowScrollTop() {
        if (document.documentElement.scrollTop > 100) {
            dispatch(actionCreators.changeShowScrollTop(true))
        } else {
            dispatch(actionCreators.changeShowScrollTop(false))
        }
    }
})

export default connect(mapState, mapDispatch)(Home)